/*
 * @(#)LoginController.java 1.0 2019年1月2日下午2:20:48
 *
 * 
 * Copyright (c) , Inc. All rights reserved.
 */
package com.saturn.config.server.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.saturn.config.server.base.dto.LoginResult;
import com.saturn.config.server.base.entity.SysUser;
import com.saturn.config.server.service.SysUserService;
import com.saturn.config.server.util.EncryptUtils;

/**
 * <dl>
 *    <dt><b>Title:</b></dt>
 *    <dd>
 *    	none
 *    </dd>
 *    <dt><b>Description:</b></dt>
 *    <dd>
 *    	<p>none
 *    </dd>
 * </dl>
 *
 * @author tanks
 * @version 1.0, 2019年1月2日
 * @since JdbcConfigServer
 * 
 */
@RestController
public class LoginController {
	
	@Autowired
	private SysUserService sysUserService;

	@CrossOrigin
	@RequestMapping(value = "/login", method=RequestMethod.POST, produces = "application/json")
	public LoginResult login(HttpServletRequest request,@RequestParam String loginName,@RequestParam String loginPassword) {
		LoginResult jsonResult = new LoginResult();
		if( StringUtils.isBlank(loginName) || StringUtils.isBlank(loginPassword) ) {
			jsonResult.setRespMsg("用户名或密码不能为空");
			return jsonResult;
		}
		QueryWrapper<SysUser> queryWrapper = Wrappers.query();
		queryWrapper.eq("user_name", loginName);
		SysUser sysUser = sysUserService.getOne(queryWrapper);
		if( sysUser==null ) {
			jsonResult.setRespMsg("用户不存在");
			return jsonResult;
		}
		try {
			if( !sysUser.getPassword().equals(EncryptUtils.md5Digest(loginPassword)) ){
				jsonResult.setRespMsg("用户密码不正确");
				return jsonResult;
			}
		} catch (Exception e) {
			jsonResult.setRespMsg("用户名或密码不能为空");
			return jsonResult;
		}
		request.getSession().setAttribute("useInfo",sysUser);
		jsonResult.setSuccess(Boolean.TRUE.booleanValue());
		jsonResult.setRespMsg("登录成功！");
		request.setAttribute("useInfo", sysUser);
		return jsonResult;
	}
	
	@CrossOrigin
	@RequestMapping(value = "/getUserInfo", produces = "application/json")
	public Object getUserInfo(HttpServletRequest request) {
		return request.getSession().getAttribute("useInfo");
	}
	
	@CrossOrigin
	@RequestMapping(value = "/logout")
	public void logout(HttpServletRequest request,HttpServletResponse response) throws Exception {
		request.getSession().removeAttribute("useInfo");
		response.sendRedirect("/static/login.html");
	}
	
}
